﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using BusinessObject;
using Utility;
using System.Web.Security;
using System.Resources;
namespace WebTeamplate
{

    public partial class Admin_DMPhieuNhapHang : BasePage
    {
        #region Fields
        public string urlDetail = "ChiTietPhieuNhapHang.aspx";
        int count = 0;
        public double thanhTien;
        public string strThanhTien = string.Empty;
        public string strCurrency = string.Empty;
        #endregion

        #region ViewState
        public int PageIndex
        {

            get
            {

                object o = ViewState["PageIndex"];

                if (o != null) return (int)o;

                return 0;

                //a default

            }

            set { ViewState["PageIndex"] = value; }

        }
        public string SortField
        {

            get
            {
                object o = ViewState["SortField"];
                if (o != null) return (string)o;
                return string.Empty;
            }

            set { ViewState["SortField"] = value; }

        }
        public string SortExpression
        {

            get
            {
                object o = ViewState["SortExpression"];
                if (o != null) return (string)o;
                return string.Empty;
            }

            set { ViewState["SortExpression"] = value; }

        }
        #endregion

        #region Init,Load
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientDefaultButton.SetPageDefaultButton(this.Page, btnSearch.ClientID);
            if (!Page.IsPostBack)
            {
                CommonFunction.LoadSubCate(drlChungXe, CommonFunction.DEFAULT_CHUNGLOAIXE_CODE, true);
                InitData();
                GetDefaultData();
                LoadData();

            }

        }
        private void GetDefaultData()
        {
            //get query paramate
            try
            {
                drlKho.SelectedValue = CommonFunction.GetValueFromQueryString(this.Page, "kho");
            }
            catch
            {
            }
            try
            {
                drlChungXe.SelectedValue = CommonFunction.GetValueFromQueryString(this.Page, "cx");
            }
            catch
            {
            }
            txtMaMatHang.Text = CommonFunction.GetValueFromQueryString(this.Page, "mamh");
            txtMaPhuTung.Text = CommonFunction.GetValueFromQueryString(this.Page, "mapt");
            txtNgayNhapFrom.Text = CommonFunction.GetValueFromQueryString(this.Page, "sdate");
            txtNgayNhapTo.Text = CommonFunction.GetValueFromQueryString(this.Page, "edate");
            try
            {
                drlCurency.SelectedValue = CommonFunction.GetValueFromQueryString(this.Page, "c");
            }
            catch
            {
            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitTextControl();
            this.imgNgayNhapSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgNgayNhapSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;
            this.imgKhoSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgKhoSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;

            this.imgNguoiNhapSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgNguoiNhapSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;

            imgNgayNhapSortDown.Click += new ImageClickEventHandler(imgNgayNhapSortDown_Click);
            imgNgayNhapSortUp.Click += new ImageClickEventHandler(imgNgayNhapSortUp_Click);
            imgKhoSortDown.Click += new ImageClickEventHandler(imgKhoSortDown_Click);
            imgKhoSortUp.Click += new ImageClickEventHandler(imgKhoSortUp_Click);
            imgNguoiNhapSortDown.Click += new ImageClickEventHandler(imgNguoiNhapSortDown_Click);
            imgNguoiNhapSortUp.Click += new ImageClickEventHandler(imgNguoiNhapSortUp_Click);
        }

        void imgNguoiNhapSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "p.Name";
            this.SortExpression = "DESC";
            LoadData();
        }

        void imgNguoiNhapSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "p.Name";
            this.SortExpression = "ASC";
            LoadData();
        }

        void imgKhoSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "k.SubCategoryName";
            this.SortExpression = "DESC";
            LoadData();
        }

        void imgKhoSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "k.SubCategoryName";
            this.SortExpression = "ASC";
            LoadData();
        }
        #endregion

        #region Methods

        public void InitTextControl()
        {
            btnSearch.Text = Resources.Resource.LABEL_BUTTON_SEARCH;
            btnReset.Text = Resources.Resource.LABEL_BUTTON_RESET;
            btnAddNew.Text = Resources.Resource.LABEL_BUTTON_ADDNEW;
            btnDelete.Text = Resources.Resource.LABEL_DELETE;
           
            this.SortExpression = "DESC";
            this.SortField = "NgayNhap";
        }
        private void InitData()
        {
            vsumSumary.ValidationGroup =cusvNgayNhapFrom.ValidationGroup=cusvNgayNhapTo.ValidationGroup= btnSearch.ValidationGroup = "phieuhang";
            cusvNgayNhapFrom.ErrorMessage =cusvNgayNhapTo.ErrorMessage= string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblNgayNhap));
            cusvNgayNhapFrom.ValidationGroup =cusvNgayNhapTo.ValidationGroup= "phieuhang";
            this.PageIndex = 1;
            Pager1.PageSize = CommonFunction.DEFAULT_ADMIN_PAGE_SIZE;
            Pager2.PageSize = CommonFunction.DEFAULT_ADMIN_PAGE_SIZE;
            CommonFunction.LoadSubCate(drlKho, CommonFunction.DEFAULT_WAREHOUSE_CODE, true);
            //CommonFunction.LoadSubCate(drlCurency, CommonFunction.DEFAULT_CURENCY_CODE, true);
            LoadCurency();
        }
        private void LoadCurency()
        {
            
            List<CurencyResult> lstData = CurencyUtil.GetAll();
            ListItem nullItem = new ListItem(BaseFunctions.COMBOBOX_NULL_VALUE, string.Empty);
             drlCurency.Items.Add(nullItem);
            
            if (lstData == null)
                return;
            foreach (CurencyResult objCate in lstData)
            {
                drlCurency.Items.Add(new ListItem(objCate.Name, objCate.Code.ToString()));
            }
            
        }
        void imgNgayNhapSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "NgayNhap";
            this.SortExpression = "DESC";
            LoadData();
        }

        void imgNgayNhapSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "NgayNhap";
            this.SortExpression = "ASC";
            LoadData();
        }

        public void LoadData()
        {
            if(drlCurency.SelectedValue!=string.Empty)
                thanhTien = 0;
            hidListId.Value = string.Empty;
            hidListIdSelect.Value = string.Empty;
            PhieuNhapHang objPhieuNhap = new PhieuNhapHang();
            objPhieuNhap.ObjectSortOrder.SortExpression = this.SortExpression;
            objPhieuNhap.ObjectSortOrder.SortField = this.SortField;
            objPhieuNhap.ObjectPaging.PageIndex = this.PageIndex;
            objPhieuNhap.ObjectPaging.PageSize = Pager1.PageSize;
            //objPhieuNhap.Condition = " where categoryId='" + CommonFunction.DEFAULT_WAREHOUSE_CODE + "'";
            objPhieuNhap.Condition = " where 1=1 ";
            if (drlKho.SelectedValue != string.Empty)
                objPhieuNhap.Condition += " and ph.maKho=" + drlKho.SelectedValue;
            if (drlChungXe.SelectedValue != string.Empty)
                objPhieuNhap.Condition += " and [dbo].[fcGetChungXePhieuNhapHang](ph.MaPhieuNhapHang)=" + drlChungXe.SelectedValue;
            if (txtMaMatHang.Text != string.Empty)
                objPhieuNhap.Condition += " and [dbo].[fcMaMatHangInPhieuNhapHang]('" + txtMaMatHang.Text.Trim() + "',ph.MaPhieuNhapHang)=1";
            if (txtMaPhuTung.Text != string.Empty)
                objPhieuNhap.Condition += " and [dbo].[fcMaPhuTungInPhieuNhapHang]('" + txtMaPhuTung.Text.Trim() + "',ph.MaPhieuNhapHang)=1";
            if (drlCurency.SelectedValue != string.Empty)
                objPhieuNhap.Condition += " and [dbo].[fcCurrencyInPhieuNhapHang]('" + drlCurency.SelectedValue + "',ph.MaPhieuNhapHang)=1";
            if (txtNgayNhapFrom.Text != string.Empty)
            {
                DateTime dt = ConvertValueObject.ParseDateTime(txtNgayNhapFrom.Text);
                objPhieuNhap.Condition += " and DATEDIFF(day,'" + dt.Year + "-" + dt.Month + "-" + dt.Day +"',ph.ngayNhap)>=0";
            }
            if (txtNgayNhapTo.Text != string.Empty)
            {
                DateTime dt = ConvertValueObject.ParseDateTime(txtNgayNhapTo.Text);
                objPhieuNhap.Condition += " and DATEDIFF(day,'" + dt.Year + "-" + dt.Month + "-" + dt.Day + "',ph.ngayNhap)<=0";
            }
            if (drlStatus.SelectedValue != string.Empty)
            {
                objPhieuNhap.Condition += " and isCommit=" + drlStatus.SelectedValue;
            }
            List<PhieuNhapHangResult> lstResult = PhieuNhapHangUtil.SearchPhieuNhapHangSomeCondition(objPhieuNhap);
            if (lstResult != null && lstResult.Count > 0)
                count = lstResult.Count;
            rptData.DataSource = lstResult;
            rptData.DataBind();
            Pager1.SetPaging(this.PageIndex, count, objPhieuNhap.ToltalRow);
            Pager2.SetPaging(this.PageIndex, count, objPhieuNhap.ToltalRow);
            if (drlCurency.SelectedValue != string.Empty)
            {
                Curency objCurency = CurencyUtil.Get(drlCurency.SelectedValue);
                if (objCurency != null)
                    strCurrency = objCurency.Name;
                strThanhTien = ConvertValueObject.ParseString(thanhTien) + " " + strCurrency;
                
            }
        }
        private void Delete(string id)
        {
            if (PhieuNhapHangUtil.Delete(ConvertValueObject.ParseLong(id)))
                LoadData();
        }
        private void Commit(string id)
        {
            if (PhieuNhapHangUtil.CommitPhieuNhapHang(ConvertValueObject.ParseLong(id),this.userLoginName,CommonFunction.Now))
                LoadData();
        }

        #endregion

        #region Events,Handler
        protected void drlLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }
        protected void rptData_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                PhieuNhapHangResult cate = (PhieuNhapHangResult)e.Item.DataItem;
                if (cate == null)
                    return;
                thanhTien += cate.ThanhTien;
                Literal ltr = (Literal)e.Item.FindControl("ltrNo");
                ltr.Text = (e.Item.ItemIndex + 1).ToString();

                //ltr = (Literal)e.Item.FindControl("ltrSubCode");
                string url = urlDetail + "?id=" + cate.MaPhieuNhapHang + "&act=" + CommonFunction.DEFAULT_COMMAND_EDIT;
                //ltr.Text = "<a href='" + url + "'>" + Server.HtmlEncode(cate.SubCategoryCode) + "</a>";
                ltr = (Literal)e.Item.FindControl("ltrNgayNhap");
                ltr.Text =ConvertValueObject.ParseString(cate.NgayNhap);

                ltr = (Literal)e.Item.FindControl("ltrNguoiNhap");
                ltr.Text = cate.NguoiNhap;

                ltr = (Literal)e.Item.FindControl("ltrKho");
                ltr.Text =Server.HtmlEncode(cate.TenKho);
                ltr = (Literal)e.Item.FindControl("ltrThanhTien");
                ltr.Text = ConvertValueObject.ParseString(cate.ThanhTien);
                Curency objCurency = PhieuNhapHangUtil.GetCurencyForPhieuNhapHang(cate.MaPhieuNhapHang);
                if (objCurency != null)
                    ltr.Text += " " + objCurency.Name;
                HyperLink hplEdit = (HyperLink)e.Item.FindControl("hplEdit");
                ltr = (Literal)e.Item.FindControl("ltrStatus");
                LinkButton lbtnDelete = (LinkButton)e.Item.FindControl("lbtnDelete");
                if (cate.IsCommit)
                {
                    hplEdit.Enabled = false;
                    hplEdit.NavigateUrl = "#";
                    ltr.Text = "Đã chốt sổ";
                    lbtnDelete.Enabled = false;
                    lbtnDelete.Visible = false;
                }
                else
                {
                    lbtnDelete.Enabled = true;
                    hplEdit.NavigateUrl = url;
                    ltr.Text = "Chưa chốt sổ";
                }
                hplEdit.Visible = false;
              
                //lbtnDelete.Visible = false;
                lbtnDelete.Text = Resources.Resource.LABEL_DELETE;
                lbtnDelete.CommandArgument = cate.MaPhieuNhapHang.ToString();
                hidListId.Value += cate.MaPhieuNhapHang + ";";

                ImageButton imgButton = (ImageButton)e.Item.FindControl("btnPublish");
                imgButton.CommandArgument = cate.MaPhieuNhapHang.ToString();
                if (cate.IsCommit)
                {
                    imgButton.Visible = false;
                }
                else
                    imgButton.ImageUrl = CommonFunction.DEFAULT_DEACTIVE_IMAGEURL;

            }
        }
        protected void rptData_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
               
                case "delete":
                    {
                        Delete(id);
                        break;
                    }
                case "commit":
                    {
                        Commit(id);
                        break;
                    }
               
            }

        }

      
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.SortExpression = "ASC";
            this.SortField = "[Order]";
            //reset sort order
            this.PageIndex = 1;
            LoadData();
        }
      

        protected void Pager1_PageIndexChanging(object obj, PagerControl.PageIndexChangeEventArgs e)
        {
            this.PageIndex = e.newPageIndex;
            LoadData();
        }
        protected void Pager1_PageSizeChanging(object obj, PagerControl.PageSizeChangeEventArgs e)
        {
            this.PageIndex = 1;
            //  this.PageSize = e.newPageSize;
            Pager2.PageSize = e.newPageSize;
            LoadData();
        }
        protected void Pager2_PageSizeChanging(object obj, PagerControl.PageSizeChangeEventArgs e)
        {
            this.PageIndex = 1;
            //  this.PageSize = e.newPageSize;
            Pager1.PageSize = e.newPageSize;
            LoadData();
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect(urlDetail);
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {         
            string[] arr = hidListIdSelect.Value.Split(';');
            for (int i = 0; i < arr.Length-1; i++)
            {
                if (arr[i].ToString() != string.Empty)
                    PhieuNhapHangUtil.Delete(ConvertValueObject.ParseInt(arr[i].ToString()));                                    
            }            
            LoadData();
        }
        #endregion
    }
}
